package reflecttest;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class ExtendedObjectPoolFactory {
    private Map<String, Object> objectPool = new HashMap<>();
    private Properties config = new Properties();



    public void init(String fileName) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        try {
            FileInputStream fis = new FileInputStream(fileName);
            //根据配置文件初始化属性
            config.load(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Object createObject(String clazzName) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        Class<?> clazz = Class.forName(clazzName);
        return clazz.newInstance();
    }

    public void initPool() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        for (String name:config.stringPropertyNames()) {
           if (!name.contains("%")){
               objectPool.put(name,createObject(config.getProperty(name)));
           }
        }
    }

    public void initProperty() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        for (String name :config.stringPropertyNames()){
            if (name.contains("%")){
                String[] objAndProp = name.split("%");
                Object target = getObject(objAndProp[0]);
                //该方法对应的方法名为：set+"属性首字母大写"+剩下部分
                String mtdName = "set"+objAndProp[1].substring(0,1).toUpperCase()+objAndProp[1].substring(1);
                Class<?> targetClass = target.getClass();
                Method mtd = targetClass.getMethod(mtdName,String.class);
                mtd.invoke(target,config.getProperty(name));
            }
        }
    }

    public Object getObject(String name){
        return objectPool.get(name);
    }

    public static void main(String[] args) throws IllegalAccessException, ClassNotFoundException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        ExtendedObjectPoolFactory pf = new ExtendedObjectPoolFactory();
        pf.init("obj.txt");
        pf.initPool();
        pf.initProperty();
        System.out.println(pf.getObject("a"));
        System.out.println(pf.getObject("b"));
    }
}
